package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AsserUtil;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
//@Transactional  暂时先别管事务
public class UserInfoServiceImpl implements IUserInfoService {



    @Autowired
    private UserInfoRepository repository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void sendVerifyCode(String phone,String smsUrl,String smsAppkey) {
        //需求:1分钟只能发送2短信
        //通过缓存服务,判断是否允许发短信,不允许则会抛异常
        userInfoRedisService.checkLimit(phone);
        //检测通过,通过UUID生成验证码
        String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        //拼短信
        StringBuilder message = new StringBuilder("【叩丁狼】您的验证码为:" + substring).append("有效期").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟");
        //发送给用户的手机
       /* System.out.println("=================华丽的分割线====================");
        RestTemplate restTemplate = new RestTemplate();
        //https://way.jd.com/chuangxin/dxjk?mobile={1}&content={2}&appkey={3}
        String result = restTemplate.getForObject(smsUrl, String.class,phone,message,smsAppkey);
        System.out.println(result);
        if (!result.contains("Success")){
            throw new LogicException("验证码发送失败");
        }
        System.out.println("=================华丽的分割线====================");*/
        System.out.println(message);
        //添加到Redis缓存
        userInfoRedisService.setVerifyCode(phone, substring);
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo byPhone = repository.findByPhone(phone);
        return byPhone != null;
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //首先,不能为空
        AsserUtil.hasLength(phone, "电话不能为空");
        AsserUtil.hasLength(nickname, "用户名不能为空");
        AsserUtil.hasLength(password, "密码不能为空");
        AsserUtil.hasLength(rpassword, "确认密码不能为空");
        AsserUtil.hasLength(verifyCode, "验证码不能为空");
        //其次,检查密码与确认密码的合理性
        AsserUtil.isEquals(password, rpassword, "两次密码不一致");
        //再之,检查电话号码是否符合格式
        AsserUtil.checkMobileNumber(phone);
        //再之检查手机号唯一
        if (this.checkPhone(phone)) {
            throw new LogicException("手机号已被注册");
        }
        //检查验证码是否一致
        String code = userInfoRedisService.getVerifyCode(phone);
        if (verifyCode==null||!verifyCode.equalsIgnoreCase(code)){
            throw new LogicException("验证码错误");
        }

        //全部通过,则进行注册
        UserInfo userInfo = new UserInfo();
        userInfo.setCity("");
        userInfo.setEmail("");
        userInfo.setNickname(nickname);
        userInfo.setPassword(password);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setLevel(1);
        userInfo.setInfo("");
        userInfo.setPhone(phone);
        userInfo.setState(UserInfo.STATE_NORMAL);

        //保存到mongodb数据库
        repository.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        //先判定用户名密码不为空
        AsserUtil.hasLength(username, "账号不能为空");
        AsserUtil.hasLength(password, "密码不能为空");
        //根据用户名查user对象
        UserInfo user = repository.findByPhone(username);
        if (user==null||!user.getPassword().equals(password)){
            //返回用户名或密码错误异常
            throw new LogicException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public UserInfo get(String userId) {
        return repository.findById(userId).get();
    }

    @Override
    public List<UserInfo> queryByCityName(String keyword) {

        return repository.findByCity(keyword);
    }
}
